//
//  File.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/9/1.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import Foundation

extension String {
    
    /// 查找字符串中的超链接和其标题文字
    ///
    /// - Returns: 通过元组返回获取结果
    func zn_getHrefAndTitle() -> (link: String, source: String)? {
        
        // 1. 设置正则匹配条件
        // (.*?)取出感兴趣的内容，.*?过滤无关内容
        let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
        
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []),
              let result = regx.firstMatch(in: self, options: [], range: NSRange(location: 0, length: characters.count))
        else {
            return nil
        }
        
        let link = (self as NSString).substring(with: result.rangeAt(1))
        let source = (self as NSString).substring(with: result.rangeAt(2))
        
        return (link, source)
    }
}
